import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from ping import Ui_MainWindow
import threading
import subprocess
import time
from queue import Queue

ipSuccess = []
ipFaild = []
Work_Thread = 254
ipQueue = Queue()


class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)
        self.statusbar.showMessage("在线台数:0")

    def on_ping_clicked(self):
        start_time = time.time()
        a = self.ip_line.text()
        if len(a) > 0 and a.split('.')[-1] == '':
            for i in range(1, 255):
                ipQueue.put(a + str(i))
            threads = []
            for i in range(Work_Thread):
                thread = threading.Thread(target=pingIp)
                thread.start()
                threads.append(thread)
            for thread in threads:
                thread.join()
            for i in ipSuccess:
                ip_green = 'ip_' + str(i.split(a)[1])
                ui_info = 'ui.' + ip_green + \
                    '.setStyleSheet("background-color:green")'
                eval(ui_info)

            time_info = format(time.time() - start_time, '.2f')
            statusbar_info = '在线台数:' + \
                str(len(ipSuccess)) + ' '*5+'执行耗时:' + time_info + 'ms'
            ui.statusbar.showMessage(statusbar_info)
            ipSuccess.clear()

        else:
            QMessageBox.information(self, "温馨提示", "请输入正确的IP网段信息!",)


def pingIp():
    while not ipQueue.empty():
        ip = ipQueue.get()
        res = subprocess.call('ping -n 2 -w 5 %s' %
                              ip, stdout=subprocess.PIPE)
        # print(ip, True if res == 0 else False)
        if res == 0:
            ipSuccess.append(ip)
        else:
            ipFaild.append(ip)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = MyMainWindow()
    ui.show()
    sys.exit(app.exec_())
